package com.cyan.note.controller;

import com.cyan.note.common.ApiResult;
import com.cyan.note.dto.admin.ShopCreateRequest;
import com.cyan.note.dto.admin.ShopResponse;
import com.cyan.note.dto.admin.ShopUpdateRequest;
import com.cyan.note.service.ShopService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.List;

/**
 * 超级管理员 - 店铺管理控制器
 * 严格按照RBAC权限控制，只有超级管理员可以访问
 * 严格遵循数据隔离原则，只能管理店铺的系统级基础信息
 * 
 * @author ZhangzhenYu
 * @since 2025-01-14
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/shops")
@RequiredArgsConstructor
@Validated
public class AdminShopController {

    private final ShopService shopService;

    /**
     * 查询所有店铺列表（仅基础信息）
     * 权限：仅超级管理员
     */
    @GetMapping
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<List<ShopResponse>> getAllShops() {
        try {
            log.info("超级管理员查询所有店铺列表");
            List<ShopResponse> shops = shopService.getAllShops();
            return ApiResult.success("查询店铺列表成功", shops);
        } catch (Exception e) {
            log.error("查询店铺列表失败", e);
            return ApiResult.error("查询店铺列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据状态查询店铺列表
     * 权限：仅超级管理员
     */
    @GetMapping("/status/{status}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<List<ShopResponse>> getShopsByStatus(
            @PathVariable @NotBlank(message = "状态不能为空") String status) {
        try {
            log.info("超级管理员按状态查询店铺列表, status: {}", status);
            List<ShopResponse> shops = shopService.getShopsByStatus(status);
            return ApiResult.success("按状态查询店铺成功", shops);
        } catch (IllegalArgumentException e) {
            log.warn("按状态查询店铺参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("按状态查询店铺失败", e);
            return ApiResult.error("按状态查询店铺失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询店铺详情
     * 权限：仅超级管理员
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<ShopResponse> getShopById(
            @PathVariable @NotNull(message = "店铺ID不能为空") Long id) {
        try {
            log.info("超级管理员查询店铺详情, shopId: {}", id);
            ShopResponse shop = shopService.getShopById(id);
            return ApiResult.success("查询店铺详情成功", shop);
        } catch (IllegalArgumentException e) {
            log.warn("查询店铺详情参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("查询店铺详情业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("查询店铺详情失败", e);
            return ApiResult.error("查询店铺详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建新店铺
     * 权限：仅超级管理员
     */
    @PostMapping
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<ShopResponse> createShop(@Valid @RequestBody ShopCreateRequest request) {
        try {
            log.info("超级管理员创建新店铺, name: {}, code: {}", request.getName(), request.getCode());
            ShopResponse shop = shopService.createShop(request);
            return ApiResult.success("创建店铺成功", shop);
        } catch (RuntimeException e) {
            log.warn("创建店铺业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建店铺失败", e);
            return ApiResult.error("创建店铺失败: " + e.getMessage());
        }
    }

    /**
     * 更新店铺基础信息
     * 权限：仅超级管理员
     */
    @PutMapping
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<ShopResponse> updateShop(@Valid @RequestBody ShopUpdateRequest request) {
        try {
            log.info("超级管理员更新店铺信息, shopId: {}", request.getId());
            ShopResponse shop = shopService.updateShop(request);
            return ApiResult.success("更新店铺信息成功", shop);
        } catch (RuntimeException e) {
            log.warn("更新店铺信息业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新店铺信息失败", e);
            return ApiResult.error("更新店铺信息失败: " + e.getMessage());
        }
    }

    /**
     * 更新店铺状态
     * 权限：仅超级管理员
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<String> updateShopStatus(
            @PathVariable @NotNull(message = "店铺ID不能为空") Long id,
            @RequestParam @NotBlank(message = "状态不能为空") String status) {
        try {
            log.info("超级管理员更新店铺状态, shopId: {}, status: {}", id, status);
            boolean success = shopService.updateShopStatus(id, status);
            if (success) {
                return ApiResult.success("店铺状态更新成功");
            } else {
                return ApiResult.error("店铺状态更新失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("更新店铺状态参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("更新店铺状态业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新店铺状态失败", e);
            return ApiResult.error("更新店铺状态失败: " + e.getMessage());
        }
    }

    /**
     * 删除店铺
     * 权限：仅超级管理员
     * 警告：这是系统级删除操作，会级联删除所有相关数据
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<String> deleteShop(
            @PathVariable @NotNull(message = "店铺ID不能为空") Long id) {
        try {
            log.warn("超级管理员删除店铺, shopId: {}", id);
            boolean success = shopService.deleteShop(id);
            if (success) {
                return ApiResult.success("店铺删除成功");
            } else {
                return ApiResult.error("店铺删除失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("删除店铺参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("删除店铺业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("删除店铺失败", e);
            return ApiResult.error("删除店铺失败: " + e.getMessage());
        }
    }

    /**
     * 检查店铺编号是否已存在
     * 权限：仅超级管理员
     */
    @GetMapping("/check-code/{code}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<Boolean> checkShopCode(
            @PathVariable @NotBlank(message = "店铺编号不能为空") String code,
            @RequestParam(required = false) Long excludeId) {
        try {
            log.info("超级管理员检查店铺编号是否存在, code: {}, excludeId: {}", code, excludeId);
            boolean exists;
            if (excludeId != null && excludeId > 0) {
                exists = shopService.isCodeExists(code, excludeId);
            } else {
                exists = shopService.isCodeExists(code);
            }
            return ApiResult.success("检查完成", exists);
        } catch (Exception e) {
            log.error("检查店铺编号失败", e);
            return ApiResult.error("检查店铺编号失败: " + e.getMessage());
        }
    }
}